Model Devlopment

How do you prepare and explore the Wine Quality dataset?


  • Set the notebook Environment version to 4 as required by the course, then import Wine Quality Data through Marketplace → Get instant access → Open. Inspect the shared catalog databricks_wine_quality_data.v01 and identify the actual table name in Catalog Explorer.
  • Read the table with Spark, inspect its schema and descriptive statistics, then convert to Pandas only if the dataset fits in driver memory:
source = "databricks_wine_quality_data.v01.<table_name>"  # Replace with actual table.
df = spark.table(source)
df.printSchema()
display(df.describe())
pdf = df.toPandas()
print(pdf.describe())
  • In a notebook result, use + → Data Profile (where available) to inspect distributions, nulls and outliers. Look for missing pH, duplicate wine_id values, and unexpected quality values before training.
  • Group pH statistics by wine quality to compare distributions:
from pyspark.sql import functions as F
stats = df.groupBy("quality").agg(
    F.count("*").alias("count"),
    F.expr("percentile(pH, 0.25)").alias("q1_pH"),
    F.expr("percentile(pH, 0.5)").alias("median_pH"),
    F.expr("percentile(pH, 0.75)").alias("q3_pH")
)
display(stats)
  • In the visualization editor, choose Bubble: X = quality, Y = median_pH, bubble size = count (and group by count if required by the course UI). Larger bubbles indicate more records, not necessarily higher pH.

How do you engineer and save a feature in Unity Catalog?


  • Feature engineering turns raw columns into model-ready inputs. This lab derives a categorical pHCategory from dataset-wide pH quartiles.
  • Calculate Q1 and Q3 and apply mutually exclusive thresholds. Use <= Q1 for Low, >= Q3 for High, and the remaining values for Average; null pH values should be handled explicitly.
from pyspark.sql import functions as F
q1, q3 = df.approxQuantile("pH", [0.25, 0.75], 0.0)
features = df.withColumn(
    "pHCategory",
    F.when(F.col("pH").isNull(), F.lit(None).cast("string"))
     .when(F.col("pH") <= q1, "Low")
     .when(F.col("pH") >= q3, "High")
     .otherwise("Average")
)
  • Verify wine_id exists, is unique and is non-null; a feature table’s primary key identifies the entity whose features are stored. If the Marketplace data has no wine_id, create a stable identifier in the preparation step rather than assuming one exists.
  • Create the catalog/schema first if needed and if you have permission, then register a Unity Catalog feature table:
from databricks.feature_engineering import FeatureEngineeringClient
fe = FeatureEngineeringClient()
fe.create_table(
    name="dbacademy.get_started_ml.wine_quality_features",
    primary_keys=["wine_id"],
    df=features,
    description="Wine quality records with engineered pH category"
)
  • The table is backed by Delta and governed in Unity Catalog. Inspect it in Catalog Explorer and the Feature Engineering/Feature Store interface. If it already exists, use an appropriate write/update workflow rather than blindly recreating it.
  • Important ML caveat: Compute quantile thresholds on the training split only for a real predictive model, then apply the same thresholds to validation, test and serving data. Computing them across the whole dataset before splitting can cause data leakage.

What does MLflow track, and how do you inspect experiments?


  • MLflow Tracking records runs, parameters, metrics, tags, datasets and artifacts so experiments can be compared and reproduced. MLflow Models packages trained models; Model Registry versions and governs them; MLflow Projects supports reproducible execution packaging.
  • Use Experiments to compare run metrics, inspect artifacts and find model versions. A run captures the configuration and results of one training attempt.
  • Manual logging: mlflow.log_param(...), mlflow.log_metric(...), and model/artifact logging give explicit control.
  • Autologging: mlflow.sklearn.autolog() captures supported scikit-learn training parameters, metrics and model artifacts. Configure it before fitting the model; avoid logging the same model twice unnecessarily.
  • Set mlflow.set_registry_uri("databricks-uc") to register models in Unity Catalog, where model names use catalog.schema.model.

How do you train and evaluate a Random Forest classifier?


  • Read dbacademy.get_started_ml.wine_quality_features and decide what to predict. In this exercise the target is pHCategory, encoded Low → 0, Average → 1, High → 2.
  • Do not use the original pH column to predict pHCategory if the purpose is to evaluate a meaningful predictive model: the label was directly derived from pH, so that feature trivially reveals the answer. Also exclude IDs and other leakage-prone columns.
  • Split into training and test sets (80/20), preferably stratified by label, and fit a Random Forest:
import mlflow
import mlflow.sklearn
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import f1_score, classification_report
from mlflow.models import infer_signature

pdf = spark.table("dbacademy.get_started_ml.wine_quality_features").toPandas()
pdf = pdf.dropna(subset=["pHCategory"])
labels = {"Low": 0, "Average": 1, "High": 2}
y = pdf["pHCategory"].map(labels)
X = pdf.select_dtypes(include="number").drop(
    columns=["wine_id", "pH"], errors="ignore"
).fillna(0)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)
mlflow.sklearn.autolog(log_input_examples=True, silent=True)
with mlflow.start_run(run_name="get-started-with-ml-flow-run") as run:
    model = RandomForestClassifier(n_estimators=100, random_state=42)
    model.fit(X_train, y_train)
    predictions = model.predict(X_test)
    mlflow.log_metric("test_f1", f1_score(y_test, predictions, average="macro"))
    print(classification_report(y_test, predictions))
    run_id = run.info.run_id
  • Macro F1 averages F1 across classes equally; it is useful when classes are imbalanced. Also inspect the confusion matrix, per-class precision/recall and train-versus-test performance.
  • This example uses only numeric columns for simplicity; a real pipeline must encode categorical inputs, handle missing values consistently and log the full preprocessing pipeline. Ensure your chosen predictors exist and the dataset contains enough samples in each class.

How do you register and promote a model in Unity Catalog?


  • A registered model has a stable three-part name and multiple versions. An alias (such as dev or Champion) points to a chosen version and can be reassigned without changing the caller’s model name.
  • With autologging, find the model artifact from the MLflow run; its artifact path can differ by MLflow version. For legacy run-artifact registration, use a known model path:
import mlflow
from mlflow.tracking import MlflowClient
mlflow.set_registry_uri("databricks-uc")

# For MLflow versions that log a model under the run's "model" artifact:
model_uri = f"runs:/{run_id}/model"
registered = mlflow.register_model(
    model_uri=model_uri,
    name="dbacademy.get_started_ml.my_model"
)
client = MlflowClient()
client.set_registered_model_alias(
    name="dbacademy.get_started_ml.my_model",
    alias="dev",
    version=registered.version
)
  • Version caveat: Newer MLflow releases may use logged-model IDs (models:/<model_id>) rather than a runs:/.../model artifact. Inspect the logged model in the run UI and use its actual URI. If the autologged model lacks the required signature, log explicitly with an input example and infer_signature(X_train, model.predict(X_train)).
  • Verify the registered version and alias in Catalog Explorer → Models. Use permissions and controlled CI/CD or Lakeflow Jobs to promote validated versions; an alias alone is not a quality gate.

How do you deploy and monitor the trained model?


  • In Catalog Explorer, select the registered model version and choose Serve, or use Serving → Create serving endpoint. Configure the endpoint, version, compute and permissions.
  • The course suggests starting endpoint provisioning immediately after registration because it can take roughly 10–12 minutes. Reuse existing endpoints where possible; Databricks Free Edition limits serving resources and may require Scale to zero.
  • Test the endpoint with known inputs and compare predictions to local inference. Keep feature preprocessing identical in training and serving to prevent training-serving skew.
  • Track prediction latency, errors, data drift, feature quality and outcome-based accuracy. Use inference tables and Databricks Lakehouse Monitoring where available; retrain or roll back if quality degrades.
  • Recommended production practice: Deploy a reproducible code workflow that includes data preparation, training, evaluation and registration, rather than relying on manual notebook clicks.

Where can you find official guidance?